package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.I18nUpdateDTO;
import com.xbongbong.paas.script.enums.I18nHideFieldEnum;
import com.xbongbong.paas.script.enums.I18nItemUpdateEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.global.ChartCategoryEnum;
import com.xbongbong.pro.enums.menu.enums.CRMMenuEnum;
import com.xbongbong.pro.enums.menu.enums.ControlCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.DistributorMenuEnum;
import com.xbongbong.pro.enums.menu.enums.EsignMenuEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueMenuEnum;
import com.xbongbong.pro.enums.menu.enums.FundManagementMenuEnum;
import com.xbongbong.pro.enums.menu.enums.GroupMessageMenuEnum;
import com.xbongbong.pro.enums.menu.enums.JXCMenuEnum;
import com.xbongbong.pro.enums.menu.enums.JXCRemouldMenuEnum;
import com.xbongbong.pro.enums.menu.enums.MarketManagementMenuEnum;
import com.xbongbong.pro.enums.menu.enums.MarketingManagementMenuEnum;
import com.xbongbong.pro.enums.menu.enums.OrderCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.ProductMenuEnum;
import com.xbongbong.pro.enums.menu.enums.ProductPriceMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SearchCustomerMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.enums.menu.enums.WorkOrderMenuEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.ProPermissionEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.ProPermissionModel;
import com.xbongbong.sys.model.RoleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @Author
 * @create 2020-06-22 8:43
 * @Description 用于刷数据库的中英文
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/I18n")
public class I18nScriptController {

    private static final Logger LOG = LoggerFactory.getLogger(I18nScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private ChartModel chartModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private RoleModel roleModel;
    @Resource
    private ProPermissionModel proPermissionModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasMenuModel paasMenuModel;

    /**
     * 主要是用于刷数据库中常量的脚本,后续不需使用
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update/fixed", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateTableFixedValue(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        List<String> corpidList = updateDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
        }
        for (String targetCorpid : corpidList) {
            String tableName = updateDTO.getTableName();
            Map<String, Object> param = new HashMap<>(1 << 4);
            param.put("corpid", targetCorpid);
            param.put("del", DelEnum.NORMAL.getDel());
            switch (tableName) {
                case "tb_chart":
                    param.put("statisticsType", StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
                    List<ChartEntity> chartEntityList = chartModel.findEntitys(param);
                    chartEntityList.forEach(item -> {
                        if (StringUtil.isEmpty(item.getMemo())) {
                            String name = "$_{table.chart.name." + item.getSystemCode() + "}";
                            String oldName = "$_{table.chart.old_name." + item.getSystemCode() + "}";
                            if (Objects.equals(item.getName(), item.getOldName())) {
                                oldName = name;
                            }
                            chartModel.updateName(item.getId(), item.getCorpid(), name, oldName, null);
                        }
                    });
                    LOG.info(tableName + "update success size =" + chartEntityList.size());
                    break;
                case "tb_role":
                    param.put("corpid", "0");
                    List<RoleEntity> roleEntityList = roleModel.findAllRoleByCorpid(param);
                    roleEntityList.forEach(item -> roleModel.updateRoleName(item.getId(), item.getCorpid(), "$_{table.role.role_name." + item.getRoleAlias() + "}"));
                    LOG.info(tableName + "update success size =" + roleEntityList.size());
                    break;
                case "tb_pro_permission":
                    List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(param);
                    proPermissionEntityList.forEach(item -> proPermissionModel.updateName(item.getId(), "$_{table.pro_permission.name." + item.getAlias() + "}"));
                    LOG.info(tableName + "update success size =" + proPermissionEntityList.size());
                    break;
                default:
                    break;
            }
            LOG.info(targetCorpid + "公司更新完成");
        }

        return "success";
    }


    /**
     * 处理图表中用户不可编辑的图表分类
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update/name", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateName(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = updateDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
        }
        for (String targetCorpid : corpidList) {
            // 公司在白名单中
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(targetCorpid);
            if (flag) {
                LocaleContextHolder.setLocale(Locale.US);
                Map<String, Object> param = new HashMap<>(1 << 4);
                param.put("corpid", targetCorpid);
                param.put("typeIn", Arrays.asList(2, 3));
                param.put("del", DelEnum.NORMAL.getDel());

                // tb_chart_category
                List<ChartCategoryEntity> chartCategoryEntityList = chartCategoryModel.findEntitys(param);
                for (ChartCategoryEntity chartCategoryEntity : chartCategoryEntityList) {
                    ChartCategoryEnum chartCategoryEnum = ChartCategoryEnum.getByAlias(chartCategoryEntity.getAlias());
                    if (chartCategoryEnum != null) {
                        chartCategoryEntity.setNameEn(chartCategoryEnum.getName());
                    }
                }

                // 批量更新数据
                LocaleContextHolder.setLocale(Locale.CHINA);

                if (CollectionsUtil.isNotEmpty(chartCategoryEntityList)) {
                    chartCategoryModel.updateBatch(chartCategoryEntityList, targetCorpid);
                    LOG.info("tb_chart_category update success and size =" + chartCategoryEntityList.size());
                }
            } else {
                LOG.info(targetCorpid + "not in whitelist");
            }
            LOG.info(targetCorpid + "公司更新完成");
        }
        return "success";
    }

    /**
     * 修复初始化时未走国际化逻辑的错误数据,一次性消费脚本,后续不可用
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fix/attrName", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixAttrName(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        Map<String, Object> param = new HashMap<>(16);
        if (Objects.nonNull(updateDTO.getAddTimeStart())) {
            param.put("addTimeStart", updateDTO.getAddTimeStart());
        }
        param.put("del", 0);
        Integer entitysCount = paasFormModel.getEntitysCount(param);

        param.put("start", 0);
        param.put("pageNum", 1500);
        param.put("orderByStr", "id");

        Long count = 0L;
        Long idGte = 0L;
        while (true) {
            param.put("idGte", idGte);
            List<PaasFormEntityExt> paasFormEntityList = paasFormModel.findEntitys(param);
            if (paasFormEntityList == null || paasFormEntityList.size() == 0) {
                break;
            }
            idGte = paasFormEntityList.get(paasFormEntityList.size() - 1).getId();
            count = count + paasFormEntityList.size();
            LOG.info("fix data process: " + count + "/" + entitysCount);
            // 修复tb_paas_form表中的custom_title、summary、labels字段
            for (PaasFormEntityExt paasFormEntity : paasFormEntityList) {
                if (Objects.nonNull(paasFormEntity.getCustomTitle()) && !Objects.equals(paasFormEntity.getCustomTitle(), "")) {
                    List<JSONObject> customTitle = JSON.parseArray(paasFormEntity.getCustomTitle(), JSONObject.class);
                    for (JSONObject object : customTitle) {
                        String attrName = I18nMessageUtil.getMessage(object.getString("attrName"));
                        object.put("attrName", attrName);
                    }
                    paasFormEntity.setCustomTitle(JSON.toJSONString(customTitle));
                }

                if (Objects.nonNull(paasFormEntity.getSummary()) && !Objects.equals(paasFormEntity.getSummary(), "")) {
                    List<JSONObject> summary = JSON.parseArray(paasFormEntity.getSummary(), JSONObject.class);
                    for (JSONObject object : summary) {
                        String attrName = I18nMessageUtil.getMessage(object.getString("attrName"));
                        object.put("attrName", attrName);
                    }
                    paasFormEntity.setSummary(JSON.toJSONString(summary));
                }

                if (Objects.nonNull(paasFormEntity.getLabels()) && !Objects.equals(paasFormEntity.getLabels(), "")) {
                    List<JSONObject> labels = JSON.parseArray(paasFormEntity.getLabels(), JSONObject.class);
                    for (JSONObject object : labels) {
                        String attrName = I18nMessageUtil.getMessage(object.getString("attrName"));
                        object.put("attrName", attrName);
                    }
                    paasFormEntity.setLabels(JSON.toJSONString(labels));
                }
            }
            paasFormModel.updateBatchTemp(paasFormEntityList);
        }

        LOG.info("fix data success");
        return "success";
    }

    /**
     * 修复表单解释的用户不可见，不可编辑的字段的国际化问题（字段在列表页展示）
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fix/hideField", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixHideField(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = updateDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
        }
        for (String targetCorpid : corpidList) {
            // 公司在白名单中
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(targetCorpid);
            if (flag) {
                try {
                    Map<String, Object> param = new HashMap<>(16);
                    param.put("corpid", targetCorpid);
                    param.put("del", DelEnum.NORMAL.getDel());
                    List<Integer> allBusinessType = updateDTO.getBusinessTypeList();
                    if (CollectionsUtil.isEmpty(allBusinessType)) {
                        allBusinessType = I18nHideFieldEnum.getAllBusinessType();
                        if (allBusinessType.contains(XbbRefTypeEnum.WORK_ORDER.getCode())) {
                            List<WorkOrderExplainEntity> workOrderExplains = workOrderExplainModel.findEntitys(param);
                            if (CollectionsUtil.isNotEmpty(workOrderExplains)) {
                                for (WorkOrderExplainEntity workOrderExplain : workOrderExplains) {
                                    Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplain.getExplains(), null);
                                    List<I18nHideFieldEnum> workOrderHideFields = I18nHideFieldEnum.getByBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                                    for (I18nHideFieldEnum hideFieldEnum : workOrderHideFields) {
                                        if (explainMap.containsKey(hideFieldEnum.getAttr())) {
                                            FieldAttrEntity fieldAttrEntity = explainMap.get(hideFieldEnum.getAttr());
                                            fieldAttrEntity.setAttrNameEn(hideFieldEnum.getAttrNameEn());
                                        }
                                    }
                                    String explains = JSON.toJSONString(explainMap.values());
                                    workOrderExplain.setExplains(explains);
                                    workOrderExplain.setUpdateTime(DateTimeUtil.getInt());
                                }
                                workOrderExplainModel.updateBatch(workOrderExplains, targetCorpid);
                            }
                        }
                    }
                    param.put("businessTypeIn", allBusinessType);
                    List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.findEntitys(param);
                    if (CollectionsUtil.isNotEmpty(paasFormExplainEntityList)) {
                        for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntityList) {
                            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
                            List<I18nHideFieldEnum> hideFields = I18nHideFieldEnum.getByBusinessType(paasFormExplainEntity.getBusinessType());
                            for (I18nHideFieldEnum hideFieldEnum : hideFields) {
                                if (!hideFieldEnum.isHasSubForm()) {     // 没有子表单
                                    if (explainMap.containsKey(hideFieldEnum.getAttr())) {
                                        FieldAttrEntity fieldAttrEntity = explainMap.get(hideFieldEnum.getAttr());
                                        fieldAttrEntity.setAttrNameEn(hideFieldEnum.getAttrNameEn());
                                    }
                                } else {     // 有子表单
                                    if (explainMap.containsKey(hideFieldEnum.getAttr())) {
                                        FieldAttrEntity fieldAttrEntity = explainMap.get(hideFieldEnum.getAttr());
                                        SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                                        List<? extends FieldAttrEntity> items = subForm.getItems();
                                        String subAttr = hideFieldEnum.getSubAttr();
                                        String subAttrNameEn = hideFieldEnum.getSubAttrNameEn();
                                        for (FieldAttrEntity fieldAttrEntity1 : items) {
                                            String attr = fieldAttrEntity1.getAttr();
                                            if (subAttr != null && subAttr.equals(attr)) {
                                                fieldAttrEntity1.setAttrNameEn(subAttrNameEn);
                                            }
                                        }
                                        fieldAttrEntity.setSubForm(subForm);
                                        explainMap.put(hideFieldEnum.getAttr(), fieldAttrEntity);
                                    }
                                }

                            }
                            String explains = JSON.toJSONString(explainMap.values());
                            paasFormExplainEntity.setExplains(explains);
                            paasFormExplainEntity.setUpdateTime(DateTimeUtil.getInt());
                        }
                        paasFormExplainModel.updateBatch(paasFormExplainEntityList, targetCorpid);
                    }
                } catch (XbbException e) {
                    LOG.error(targetCorpid + "Error modifying the English name of the field");
                }
            }
        }

        LOG.info("fix data success");
        return "success";
    }

    /**
     * 修复表单解释的用户不可见，不可编辑的字段的国际化问题（字段在列表页展示）
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fix/itemCheck", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String itemCheck(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = updateDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
        }
        for (String targetCorpid : corpidList) {
            // 公司在白名单中
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(targetCorpid);
            if (flag) {
                try {
                    Map<String, Object> param = new HashMap<>(16);
                    param.put("corpid", targetCorpid);
                    param.put("del", DelEnum.NORMAL.getDel());
                    List<Integer> allBusinessType = updateDTO.getBusinessTypeList();
                    if (CollectionsUtil.isEmpty(allBusinessType)) {
                        allBusinessType = I18nHideFieldEnum.getAllBusinessType();
                        if (allBusinessType.contains(XbbRefTypeEnum.WORK_ORDER.getCode())) {
                            List<WorkOrderExplainEntity> workOrderExplains = workOrderExplainModel.findEntitys(param);
                            if (CollectionsUtil.isNotEmpty(workOrderExplains)) {
                                for (WorkOrderExplainEntity workOrderExplain : workOrderExplains) {
                                    Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplain.getExplains(), null);
                                    List<I18nHideFieldEnum> workOrderHideFields = I18nHideFieldEnum.getByBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                                    for (I18nHideFieldEnum hideFieldEnum : workOrderHideFields) {
                                        if (explainMap.containsKey(hideFieldEnum.getAttr())) {
                                            FieldAttrEntity fieldAttrEntity = explainMap.get(hideFieldEnum.getAttr());
                                            fieldAttrEntity.setAttrNameEn(hideFieldEnum.getAttrNameEn());
                                        }
                                    }
                                    String explains = JSON.toJSONString(explainMap.values());
                                    workOrderExplain.setExplains(explains);
                                    workOrderExplain.setUpdateTime(DateTimeUtil.getInt());
                                }
                                workOrderExplainModel.updateBatch(workOrderExplains, targetCorpid);
                            }
                        }
                    }
                    param.put("businessTypeIn", allBusinessType);
                    List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.findEntitys(param);
                    if (CollectionsUtil.isNotEmpty(paasFormExplainEntityList)) {
                        for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntityList) {
                            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
                            List<I18nHideFieldEnum> hideFields = I18nHideFieldEnum.getByBusinessType(paasFormExplainEntity.getBusinessType());
                            for (I18nHideFieldEnum hideFieldEnum : hideFields) {
                                if (explainMap.containsKey(hideFieldEnum.getAttr())) {
                                    FieldAttrEntity fieldAttrEntity = explainMap.get(hideFieldEnum.getAttr());
                                    fieldAttrEntity.setAttrNameEn(hideFieldEnum.getAttrNameEn());
                                }
                            }
                            String explains = JSON.toJSONString(explainMap.values());
                            paasFormExplainEntity.setExplains(explains);
                            paasFormExplainEntity.setUpdateTime(DateTimeUtil.getInt());
                        }
                        paasFormExplainModel.updateBatch(paasFormExplainEntityList, targetCorpid);
                    }
                } catch (XbbException e) {
                    LOG.error(targetCorpid + "Error modifying the English name of the field");
                }
            }
        }

        LOG.info("fix data success");
        return "success";
    }

    /**
     * 修复表单解释的用户不可见，不可编辑的字段的国际化问题（字段在列表页展示）
     *
     * @param updateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fix/NoEditable/item", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixNoEditableitem(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = updateDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
        }
        for (String targetCorpid : corpidList) {
            // 公司在白名单中
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(targetCorpid);
            if (CollectionsUtil.isEmpty(updateDTO.getBusinessTypeList())) {
                return "businessTypeList 不能为空";
            }
            if (flag) {
                try {
                    Map<String, Object> param = new HashMap<>(16);
                    param.put("corpid", targetCorpid);
                    param.put("del", DelEnum.NORMAL.getDel());
                    param.put("businessTypeIn", updateDTO.getBusinessTypeList());
                    List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.findEntitys(param);
                    if (CollectionsUtil.isNotEmpty(paasFormExplainEntityList)) {
                        for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntityList) {
                            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
                            List<I18nItemUpdateEnum> hideFields = I18nItemUpdateEnum.getByBusinessType(paasFormExplainEntity.getBusinessType());
                            Set<String> attrs = I18nItemUpdateEnum.getAttrs(paasFormExplainEntity.getBusinessType());
                            Map<String, Map<String, String>> map = new HashMap<>(attrs.size());
                            hideFields.forEach(item -> {
                                if (Objects.isNull(map.get(item.getAttr()))) {
                                    Map<String, String> test = new HashMap<>();
                                    test.put(item.getCode(), item.getNameEn());
                                    map.put(item.getAttr(), test);
                                } else {
                                    map.get(item.getAttr()).put(item.getCode(), item.getNameEn());
                                }
                            });
                            attrs.forEach(item -> {
                                FieldAttrEntity fieldAttrEntity = explainMap.get(item);
                                if (Objects.nonNull(fieldAttrEntity)) {
                                    List<ItemPoJo> items = fieldAttrEntity.getItems();
                                    items.forEach(test1 -> {
                                        if (StringUtil.isNotEmpty(map.get(item).get(test1.getValue().toString()))) {
                                            test1.setText(map.get(item).get(test1.getValue().toString()));
                                        }
                                    });
                                    fieldAttrEntity.setItems(items);
                                }
                            });
                            String explains = JSON.toJSONString(explainMap.values());
                            paasFormExplainEntity.setExplains(explains);
                            paasFormExplainEntity.setUpdateTime(DateTimeUtil.getInt());
                        }
                        paasFormExplainModel.updateBatch(paasFormExplainEntityList, targetCorpid);
                    }
                } catch (XbbException e) {
                    LOG.error(targetCorpid + "Error modifying the English name of the field");
                }
            }
        }

        LOG.info("fix data success");
        return "success";
    }

    /*
     * 刷菜单和应用脚本
     *curl http://127.0.0.1:2019/pro/v1/script/I18n/fix/menu -X POST -H 'Content-type: application/json' -d '{"corpid":"1","userId":"1","platform":"web","xbbCode":"123456","corpidList":["1","xbbhui"]}'
     * date: 2022/2/22 8:48 下午
     * @Author yingjf
     * @param updateDTO:
     * @param br:
     */
    @RequestMapping(value = "/fix/menu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixMenu(@RequestBody @Valid I18nUpdateDTO updateDTO, BindingResult br) throws Exception {
        try {
            Locale locale = LocaleContextHolder.getLocale();
            LocaleContextHolder.setLocale(Locale.US);
            // 成功数
            long successNum = 0L;
            // 失败数
            long failNum = 0L;
            Long currentTime = DateTimeUtil.getInt();
            LOG.info("系统菜单国际化执行开始");
            if (!proBaseConfig.getXbbCode().equals(updateDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
            }
            List<String> corpidList = updateDTO.getCorpidList();
            if (CollectionsUtil.isEmpty(corpidList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请填写公司名");
            }
            for (String targetCorpid : corpidList) {
                try {
                    if (StringUtil.isEmpty(targetCorpid)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "corpid有误");
                    }
                    Map<String, String> systemAppMenuEnumMap = new HashMap<>();
                    Map<String, Object> params = new HashMap<>();
                    params.put("corpid", targetCorpid);
                    params.put("saasMark", 1);
                    params.put("del", 0);
                    List<PaasAppEntity> paasAppEntities = paasAppModel.findEntitys(params);
                    // 取出应用枚举 alias作唯一标识
                    for (SystemAppMenuEnum systemAppMenuEnum : SystemAppMenuEnum.values()) {
                        String alias = systemAppMenuEnum.getAlias();
                        String nameEn = systemAppMenuEnum.getName();
                        systemAppMenuEnumMap.put(alias, nameEn);
                    }
                    List<PaasAppEntity> updatePaasAppEntities = new ArrayList<>();
                    for (PaasAppEntity paasAppEntity : paasAppEntities) {
                        String alias = paasAppEntity.getAlias();
                        String nameEn = systemAppMenuEnumMap.get(alias);
                        // 未匹配到的不更新
                        if (Objects.nonNull(nameEn)) {
                            // 重新塞入英文
                            // TODO: 2022/2/23  是否nameen不为空才刷 先不处理
                            paasAppEntity.setNameEn(nameEn);
                            updatePaasAppEntities.add(paasAppEntity);
                        }
                    }
                    // 更新应用

                    if (CollectionsUtil.isNotEmpty(updatePaasAppEntities)) {
                        LocaleContextHolder.setLocale(Locale.CHINA);
                        paasAppModel.updateBatch(updatePaasAppEntities, targetCorpid);
                        LocaleContextHolder.setLocale(Locale.US);
                    }
                    params.clear();
                    params.put("corpid", targetCorpid);
                    params.put("saasMark", 1);
                    params.put("del", 0);
                    List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(params);
                    List<PaasMenuEntity> updatePaasMenuEntities = new ArrayList<>();
                    Map<String, String> menuMap = getMenuMap();
                    for (PaasMenuEntity paasMenuEntity : paasMenuEntities) {
                        String alias = paasMenuEntity.getAlias();
                        String nameEn = menuMap.get(alias);
                        if (Objects.nonNull(nameEn)) {
                            // 重新塞入英文
                            paasMenuEntity.setNameEn(nameEn);
                            updatePaasMenuEntities.add(paasMenuEntity);
                        }
                    }
                    // 更新菜单
                    if (CollectionsUtil.isNotEmpty(updatePaasMenuEntities)) {
                        // 这里需要切换回语言  不然入库会有问题 会中英文相反
                        LocaleContextHolder.setLocale(Locale.CHINA);
                        paasMenuModel.updateBatch(updatePaasMenuEntities, targetCorpid);
                        LocaleContextHolder.setLocale(Locale.US);
                    }
                    successNum++;
                } catch (Exception e) {
                    failNum++;
                    LOG.info("corpid：{}处理异常", targetCorpid);
                    LOG.error("异常信息", e);
                }
            }
            LOG.info("处理完成，耗时{}", DateTimeUtil.getInt() - currentTime);
            LOG.info("成功{}家，失败{}家", successNum, failNum);
        } catch (Exception e) {
            LOG.error("系统菜单刷英文异常：", e);
            LocaleContextHolder.setLocale(Locale.CHINA);
            return "false";
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        return "success";
    }

    private Map<String, String> getMenuMap() {
        Map<String, String> menuEnumMap = new HashMap();
        //CallCenterMenuEnum 呼叫中心
        Arrays.asList(CRMMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //ControlCenterMenuEnum 管理中心列表枚举类
        Arrays.asList(ControlCenterMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //CRMMenuEnum crm的菜单内容
        Arrays.asList(CRMMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //DistributorMenuEnum 经销商的菜单内容
        Arrays.asList(DistributorMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //EsignMenuEnum 电子合同
        Arrays.asList(EsignMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //FineClueMenuEnum 精线索菜单
        Arrays.asList(FineClueMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //FundManagementMenuEnum 资金管理枚举类
        Arrays.asList(FundManagementMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //GroupMessageMenuEnum 短信群发
        Arrays.asList(GroupMessageMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //JXCMenuEnum  进销存菜单内容
        Arrays.asList(JXCMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //JXCRemouldMenuEnum
        Arrays.asList(JXCRemouldMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //MarketingManagementMenuEnum 经销商
        Arrays.asList(MarketingManagementMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //MarketManagementMenuEnum 市场管理
        Arrays.asList(MarketManagementMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //OrderCenterMenuEnum 经销商的菜单内容
        Arrays.asList(OrderCenterMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //ProductMenuEnum 产品
        Arrays.asList(ProductMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //ProductPriceMenuEnum
        Arrays.asList(ProductPriceMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        //SearchCustomerMenuEnum 搜客的菜单
        Arrays.asList(SearchCustomerMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        // WorkOrderMenuEnum 工单
        Arrays.asList(WorkOrderMenuEnum.values()).forEach(item -> {
            menuEnumMap.put(item.getAlias(), I18nMessageUtil.getMessage(item.getName(), Locale.US));
        });
        return menuEnumMap;
    }
}
